var mongoose = require('mongoose');
const Comment  = require('../models/comment.model');
var async = require('async');
const News = require('../models/news.model');

exports.create = function(req,res,next){
	const news = new News(req.body);

	news.save()
	.then(data=>{
		 res.json(data);
	})
}

exports.get = function(req,res,next){
	var id = req.params.id;

	News.findById(id, function (err, data) {
	  res.json(data)
	})
}

exports.update = function(req,res,next){
	// const news = new News(req.body);
	const id = req.params.id;

	News.findByIdAndUpdate(id, {$set:req.body}, {new:false})
	.then(data=>{
		res.json(data);
	})
}

exports.remove = function(req,res,next){
	const id = req.params.id;

	News.findByIdAndRemove(id,function(err,data){
		res.json(data)
	})
	
}

exports.list = function(req,res,next){
	var page = (req.body.page) ? req.body.page : 1;
	var rows = (req.body.rows) ? req.body.rows : 5;

	var queryCondition = {};
	if(req.body.name && req.body.name.trim().length>0){
		name = req.body.name;
		queryCondition = {
			"name" : new RegExp(name,'i')
		}
	}

	if(req.body.cateid && req.body.cateid.trim().length>0){
		cateid = req.body.cateid;
		queryCondition = {
			"cateid" : cateid
		}
	}
									//倒序sort
	News.paginate(queryCondition, {sort: { _id: -1}, page: parseInt(page), limit: parseInt(rows) }, function(err, result) {
	  
		async.map(result.docs,function(news,done){ //callback修改成done

			Comment.count({cateid: news._id},function(err,count){
				if(err){
					return;
				}else{
					news.commentcount = count;
					done();
					console.log(count)
				}
			})
		},function(err){
			result.rows = result.docs;
			  delete result.docs;

			  res.json(result)
		})


	  // result.rows = result.docs;
	  // delete result.docs;

	  // res.json(result)

	});
	
	// var page1 = (req.body.page) ? req.body.page : 1;
	// var rows1 = (req.body.rows) ? req.body.rows : 9999;

	// var queryCondition1 = {};
	// if(req.body.cateid && req.body.cateid.trim().length>0){
	// 	cateid = req.body.cateid;
	// 	queryCondition1 = {
	// 		"cateid" : cateid
	// 	}
	// }

	// 								//倒序sort
	// News.paginate(queryCondition1, {sort: { _id: -1}, page1: parseInt(page), limit: parseInt(rows1) }, function(err, result) {
	//   result.rows = result.docs;
	//   delete result.docs;

	//   res.json(result)

	// });

}


exports.deletes = function(req,res,next){
	// console.log(req.body)
	var ids = req.body.ids;

	if(ids.length>0){
		console.log(ids.split(','))
		News.remove({_id:{$in:ids.split(',')}})
		.then(data=>{
			res.json({"msg":"deletes success","status":200})
		})
	}else{
			res.json({"msg":"deletes fail","status":404})

	}
}







